/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.control;

import it.polimi.meteocal.entity.User;
import java.security.Principal;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author paolo
 */
@Stateless
public class UserManager {

    @PersistenceContext
    public EntityManager em;

    @Inject
    Principal principal;

    /**
     * set the groupname of the user and persist to teh database
     *
     * @param user
     */
    public void save(User user) {
        System.out.println("salvo");
        user.setGroupname("USER");
        System.out.println(user.getEmail() + " " + user.getName());
        perstitToDatabase(user);
    }

    /**
     * method that return the logged user
     */
    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }

    /**
     * change the visibility of the calendar of the logged user
     */
    public void changeVisibility() {
        System.out.println("**********CHANGEVISIBILITY***********");
        User user = this.getLoggedUser();
        if (user.getPublicCalendar()) {
            user.setPublicCalendar(Boolean.FALSE);
        } else {
            user.setPublicCalendar(Boolean.TRUE);
        }
        em.merge(user);
        em.flush();
        System.out.println(user.getPublicCalendar());
    }

    /**
     * method that control if an user is really registered to the system
     *
     * @param user the string to check
     * @return true if the user exist, false otherwise
     */
    public Boolean checkExistUser(String user) {
        return em.find(User.class, user) != null;
    }

    public User getUser(String user) {
        return em.find(User.class, user);
    }

    public void perstitToDatabase(User u) {
        em.persist(u);
        em.flush();
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public Principal getPrincipal() {
        return principal;
    }

    public void setPrincipal(Principal principal) {
        this.principal = principal;
    }

}
